package com.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.HttpUtils;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;
import com.gulimall.common.vo.SocialUser;
import com.gulimall.common.vo.UserLoginVo;
import com.gulimall.member.dao.MemberDao;
import com.gulimall.member.dao.MemberLevelDao;
import com.gulimall.member.entity.MemberEntity;
import com.gulimall.member.entity.MemberLevelEntity;
import com.gulimall.member.excetion.PhoneExistException;
import com.gulimall.member.excetion.UsernameExistExcetion;
import com.gulimall.member.service.MemberService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        String username = (String) params.get("username");
        if (!StringUtils.isEmpty(username)) {
            queryWrapper.like("username", username);
        }
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    /**
     * 注册会员业务逻辑
     *
     * @param vo
     */
    @Override
    public void regist(UserLoginVo vo) {
        System.out.println("你好！");
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();

//设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());
        //检查用户名和手机号唯一  为了让controll感知异常，使用异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getLoginacct());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getLoginacct());
        entity.setNickname(vo.getLoginacct());
        System.out.println("你好！22");
        //密码加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println(vo.toString());

        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);
        System.out.println("你好！3333");
//保存用户
        memberDao.insert(entity);
    }

    /**
     * 邮箱
     *
     * @param phone
     * @return
     */
    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    /**
     * 用户名
     *
     * @param username
     * @return
     */
    @Override
    public void checkUsernameUnique(String username) throws UsernameExistExcetion {
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (mobile > 0) {
            throw new UsernameExistExcetion();
        }
        //throw new UsernameExistExcetion();
    }

    /**
     * 登录
     *
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(UserLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
//去数据库查询
        MemberDao mapperDao = this.baseMapper;
        MemberEntity entity = mapperDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if (entity == null) {
            //登录失败
            return null;
        } else {
            //成功
            //获取到数据库的password
            String passwordDB = entity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            //2.密碼匹配
            boolean matches = encoder.matches(password, passwordDB);
            if (matches) {
                return entity;
            } else {
                return null;
            }
        }
        //return null;
    }

    /**
     * 社交登录
     *
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //登录和注册合并逻辑
        String uid = socialUser.getUid();
        //1.判断当前社交用户是否已经登录过系统
        MemberDao memberDao = this.baseMapper;
        //查询数据库中是否存在这个社交账号的uid
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        if (memberEntity != null) {
            //这个用户注册过
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpirsrdIn(socialUser.getExpires_in());
            memberDao.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpirsrdIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            //2.没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity regist = new MemberEntity();
            try {
                //3.查询当前社交用户的社交账号信息（昵称，性别等）
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    ///查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    //昵称
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    //..........
                    regist.setNickname(name);
                    regist.setUsername(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                    //...
                }
            } catch (Exception e) {
            }
            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpirsrdIn(socialUser.getExpires_in());

            memberDao.insert(regist);
            return regist;
        }
    }
}